package com.ehouse.push;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.ehouse.MainActivity;
import com.ehouse.R;
import com.google.android.gcm.GCMBaseIntentService;

public class NotificationsService extends GCMBaseIntentService{
	public interface NotificationListener{
		public void receivedRegistrationId(String regId);

	}
	
	public static final String REG_ID = "registration_id";
	public static final String LOG_ID = "push";
	
	public NotificationsService(){
		super();
	}
	
	@Override
	public void onRegistered(Context context, String regId){
		//save registration id
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
		Editor editor = sharedPrefs.edit();
    	editor.putString(NotificationsService.REG_ID, regId);
    	editor.commit();
    	
    	MainActivity.notificationsListener.receivedRegistrationId(regId);
	}
	
	@Override
	public void onUnregistered(Context context, String regId){
		//remove registration id only if it is the same
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
		if(sharedPrefs.getString(NotificationsService.REG_ID, "").equals(regId)){
			Editor editor = sharedPrefs.edit();
    		editor.putString(NotificationsService.REG_ID, "");
    		editor.commit();
		}
	}
	
	@Override
	public void onMessage(Context context, Intent intent){
		String title = intent.getStringExtra("title");
		String message = intent.getStringExtra("content");
		String 	sbadge	= intent.getStringExtra("badge");
		int badge = Integer.valueOf(sbadge);
		
		
		// create notification
		NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    	Notification notification = new NotificationCompat.Builder(context)
    	.setNumber(badge)
    	.setAutoCancel(true)
    	.setDefaults(Notification.DEFAULT_ALL)
    	.setSmallIcon(R.drawable.ic_stat_notify)
    	.setContentTitle(title)
    	.setContentText(message)
    	.build();
    	notification.contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
    	notificationManager.notify(badge, notification);
    	
    	
	}
	
	@Override
	public void onError(Context context, String errorId){
		Log.v(NotificationsService.LOG_ID, "Error with push notifications: " + errorId);
	}
}
